package com.xuyh.sign;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;

/**
 * @author xuyh
 * @version 0.0.1
 * @date 2020/11/19 11:40
 * @email xuyh0817@foxmail.com
 * @description todo
 */
@RestController
public class IndexRest {
    private final static String FILE_PATH = "D:" + File.separator + "tmp" + File.separator;
    private final static String IMAGE_PREFIX = "data:image/png;base64,";

    @PostMapping("upload")
    public Object upload(@RequestBody JSONObject body) throws Exception {
        String imageData = body.getStr("imageData");
        imageData = imageData.replace(IMAGE_PREFIX, "");
        byte[] bytes = imageData.getBytes();
        String fileName = UUID.randomUUID().toString();
        IoUtil.write(new FileOutputStream(FILE_PATH + fileName + ".png"), true, bytes);
        return fileName;
    }

    @GetMapping("view/{fileName}")
    public Object view(@PathVariable String fileName) throws Exception {
        List<File> files = FileUtil.loopFiles(FILE_PATH);
        for (File file : files) {
            if (file.getName().contains(fileName)) {
                String read = IoUtil.read(new FileInputStream(file), Charset.defaultCharset());
                return IMAGE_PREFIX + read;
            }
        }
        return "";
    }

    @RequestMapping("index")
    public Object index() {
        return DateTime.now().toString("yyyy-MM-dd HH:mm:ss");
    }
}
